/**
 * @name: TheUpload
 * @description: 上传组件封装
 * @upTime: 2023--02--06
 * @props { bool }      disabled        是否显示上传控件
 * @props { number }    len             上传数量
 * @props { string }    label           上传按钮文字
 * @props { func }      getFileResult   图片上传回调
 * @props { string }    type            上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card
 * @props { object }    data            上传所需额外参数或返回上传额外参数的方法
 * @props { string }    fileType        上传的文件格式     - 可选 video||image
 * @props { number }    maxSize         上传的文件大小     - 单位M
 * @props { number }    imgWidth        设置限制上传的图片宽度
 * @props { number }    imgHeight       设置限制上传的图片高度
 * @props { string }    mode            设置上传的图片模式  - 可选 ‘shop’
 * @props { array }     accept          控制上传的文件类型
 * @props { bool }      isConversion    是否开启转换jpg格式
 * @props { bool }      isShowRemoveIcon是否显示删除icon按钮
 * @props { array }      fileList        现有数据集合
 *
 **/

import React from 'react'
import PropTypes from 'prop-types'
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { withRouter } from 'react-router-dom'
import { getBase } from '@/utils/getBase'
import videoPng from '@/assets/images/video.png'
import Compressor from 'compressorjs';

class TheUpload extends React.Component {
    state = {
        previewVisible: false,
        previewImage: '',
        previewTitle: '',
        fileList: [],
        previewType: 'img'
    };
    componentDidUpdate(prev){
        if(prev.fileList.length!==this.props.fileList.length){
            this.setState({ fileList: this.props.fileList })
        }
    }
    componentDidMount() {
        if (this.props.fileList) {
            this.setState({ fileList: this.props.fileList })
        }
    }

    handleCancel = () => this.setState({ previewVisible: false });
    handleRemove = (file) => {
        const index = this.state.fileList.indexOf(file)
        this.state.fileList.splice(index, 1)
        this.setState({
            fileList: this.state.fileList
        }, () => {
            this.props.getFileResult(this.state.fileList)
        })
    }
    handlePreview = async file => {
        const type = this.getFileType(file.url || file.name)
        if (type === 'video') {
            this.setState({
                previewImage: file.url || file.response.data,
                previewVisible: true,
                previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
                previewType: 'video'
            });
            return
        }
        if (!file.url && !file.preview) {
            file.preview = await getBase(file.originFileObj);
        }
        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
            previewType: 'img'
        });
    };

    handleChange = ({ file, fileList, event }) => {
        const { maxSize, fileType } = this.props
        if (fileType && !['video', 'image'].includes(fileType)) {
            React.$message({
                type: 'warning',
                content: `fileType字段类型错误,仅支持image/video类型`
            })
            return
        }
        if (fileType && fileType === 'video') {
            if (file.type !== "video/mp4") return
        }
        if (fileType && fileType === 'image') {
            if (file.type && file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/webp" && file.type !== "image/svg+xml") return
        }
        if (file.type && file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "video/mp4" && file.type !== "image/webp" && file.type !== "image/svg+xml") {
            return
        }
        if (file.size / 1024 / 1024 >= (maxSize || 10)) {
            return
        }
        if (file && fileList && fileList.length) {
            fileList = fileList.map(v => {
                console.log(v)
                if (v.status === 'done' && v.response) {
                    if (v.response && v.response.code === 0 && v.response.data) {
                        return { ...v }
                    } else {
                        return {
                            ...v,
                            // uid: '-5',
                            // name: v.name,
                            status: 'error'
                        }
                    }
                } else if (v.status === 'error') {
                    return {
                        response: v.response,
                        size: v.size,
                        uid: '-5',
                        name: v.name,
                        status: 'error',
                    }
                } else {
                    return { ...v }
                }
            })
        }
        // console.log(fileList)
        //过滤数据大于10M的数据
        fileList = fileList.filter(v => (v.size / 1024 / 1024 < (maxSize || 10) || v.status === 'done'))
        this.props.getFileResult(fileList)
        this.setState({ fileList })
    };

    handlePreviewFile(file) {
        const that = this
        const fileType = this.getFileType(file.type)
        return new Promise((resolve) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                const dataUrl = e.target.result;
                if (fileType === 'video') {
                    resolve(videoPng)
                } else {
                    resolve(dataUrl)
                }
            }
        })
    }

    getFileType(str) {
        if (str.indexOf('.mp4') > -1) {
            return 'video'
        } else {
            return 'image'
        }
    }

    // 把image 转换为 canvas对象
    // imgToCanvas(image) {
    //     let canvas = document.createElement("canvas");
    //     canvas.width = image.width;
    //     canvas.height = image.height;
    //     canvas.getContext("2d").drawImage(image, 0, 0);
    //     return canvas;
    // }

    //  canvas转换为image
    // canvasToImg(canvas, type = 'jpeg') {
    //     return new Promise((resolve, reject) => {
    //         // 压缩
    //         canvas.toDataURL('image/jpeg', 0.6);
    //         canvas.toBlob((image) => {
    //             resolve(image)
    //         }, `image/${type}`)
    //     })
    // }

    // async imgTypeChange(file, image) {
    //     // 获取图片信息
    //     let imgName = file.name.split('.')[0]
    //     // 把image 转换为 canvas对象
    //     const can = this.imgToCanvas(image)
    //     // canvas转换为Bolb 类型image
    //     const blobImg = await this.canvasToImg(can, 'jpeg')
    //     return new Promise((resolve) => {
    //         resolve(new File([blobImg], `${imgName}.jpg`, {type: blobImg.type}))
    //     })
    // }

    render() {
        const { previewVisible, previewImage, fileList, previewTitle, previewType } = this.state;
        const {
            len,
            disabled,
            label,
            type,
            data,
            imgWidth,
            imgHeight,
            mode,
            fileType,
            maxSize,
            accept,
            isConversion,
            isShowRemoveIcon
        } = this.props;
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>{label}</div>
            </div>
        );
        const checkFileSize = (file) => {
            // const {fileType, maxSize, accept} = this.props
            // let isPNG = file.type === "image/png"
            // let isJPG = file.type === "image/jpg"
            // let isJPEG = file.type === "image/jpeg"
            // let isWEBP = file.type === "image/webp"
            // let isSVG = file.type === "image/svg+xml"
            // const isMp4 = file.type === "video/mp4"
            if (fileType && !['video', 'image'].includes(fileType)) {
                React.$message({
                    type: 'warning',
                    content: `fileType字段类型错误,仅支持image/video类型`
                })
                return false || Upload.LIST_IGNORE;
            }
            // if (fileType && fileType === 'video') {
            //     if (!isMp4) {
            //         React.$message({
            //             type: 'warning',
            //             content: `${file.name} 不是 mp4 文件`
            //         })
            //         return false || Upload.LIST_IGNORE;
            //     }
            // }
            // if (fileType && fileType === 'image') {
            //     if (!isPNG && !isJPG && !isJPEG && !isWEBP && !isSVG) {
            //         React.$message({
            //             type: 'warning',
            //             content: `${file.name} 不是 png,jpg,jpeg,webp,svg 文件`
            //         })
            //         return false || Upload.LIST_IGNORE;
            //     }
            // }
            // if (!isPNG && !isJPG && !isJPEG && !isWEBP && !isSVG && !isMp4) {
            //     React.$message({
            //         type: 'warning',
            //         content: `${file.name} 不是 png,jpg,jpeg,webp,svg,mp4 文件`
            //     })
            //     return false || Upload.LIST_IGNORE;
            // }
            // console.log(file.type,accept)
            if (!accept.includes(file.type)) {
                // eslint-disable-next-line array-callback-return
                let mess = []
                // eslint-disable-next-line array-callback-return
                accept.filter(item => {
                    if (item.indexOf(fileType) !== -1) {
                        mess.push(item = item.replace(new RegExp(`${fileType}/`, 'g'), '.'))
                    }
                })
                React.$message({
                    type: 'warning',
                    content: `${file.name} 不是 ${mess} 类型文件`
                })
                return false || Upload.LIST_IGNORE;
            }
            let _that = this;
            if (file.size / 1024 / 1024 < (maxSize || 5)) {
                return new Promise((resolve, reject) => {
                    const width = parseInt(imgWidth) || Infinity;
                    const height = parseInt(imgHeight) || Infinity;
                    if (file.type === 'video/mp4') {
                        const video = document.createElement('video')
                        let reader = new FileReader();
                        reader.readAsDataURL(file);
                        // console.log(file, 'file');
                        reader.onload = function (e) {
                            // console.log(e.target.result);
                            video.src = e.target.result;
                            resolve();
                        }
                    } else {
                        // let options = {
                        //     quality: 0.8, //输出的图像画质
                        //     mimeType: isConversion ? "image/jpeg" : 'auto', //输出的文件类型
                        // }
                        // new Compressor(file, {
                        //     ...options,
                        //     // The compression process is asynchronous,
                        //     // which means you have to access the `result` in the `success` hook function.
                        //     success(result) {
                        //         let nFile = new File([result], `${result.name}`, { type: result.type });
                        //         let img = new Image();
                        //         // console.log(result,nFile,getBase(result))
                        //         getBase(nFile).then((result) => {
                        //             img.src = result;
                        //         })
                        //         img.onload = async () => {
                        //             if (mode == 'shop') {
                        //                 if (img.width != img.height) {
                        //                     React.$message({
                        //                         type: 'info',
                        //                         content: `请上传宽高比例1:1的图片`
                        //                     })
                        //                     file.status = 'error'
                        //                     reject(new Error(`请上传宽高比例1:1的图片`));
                        //                 } else {
                        //                     resolve(nFile)
                        //                 }
                        //             }
                        //             else {
                        //                 if (img.width > width || img.height > height) {
                        //                     React.$message({
                        //                         type: 'info',
                        //                         content: `文件尺寸不能超过${width}*${height}`
                        //                     })
                        //                     file.status = 'error'
                        //                     reject(new Error(`文件尺寸不能超过${width}*${height}`));
                        //                 } else {
                        //                     resolve(nFile)
                        //                 }
                        //             }
                        //         }
                        //     },
                        //     error(err) {
                        //         // console.log(err.message);
                        //         file.status = 'error'
                        //         reject(new Error(err.message));
                        //     },
                        // });
                        let reader = new FileReader();
                        reader.onload = function (e) {
                            let img = new Image();
                            img.src = e.target.result;
                            img.onload = async () => {
                                resolve()
                            };
                        }
                        reader.readAsDataURL(file);
                    }
                });
            } else {
                React.$message({
                    type: 'info',
                    content: `文件最大不能超过${(maxSize || 10)}M`
                })
                return false
            }
        };

        const RSnetToken = sessionStorage.getItem('RSnetToken')
        return (
            <>
                <Upload
                    // action={React.$BaseUrl+"/oss/image/upload"}
                    action={"https://management.hqmpet.com/management/oss/image/upload"}
                    listType={type}
                    fileList={fileList}
                    accept={accept.toString()}
                    data={data}
                    headers={{ RSnetToken }}
                    beforeUpload={checkFileSize}
                    onPreview={this.handlePreview}
                    previewFile={(e) => this.handlePreviewFile(e)}
                    onRemove={this.handleRemove}
                    onChange={this.handleChange}
                    showUploadList={{showRemoveIcon:isShowRemoveIcon}}>
                    {(fileList.length >= len || disabled) ? null : uploadButton}
                </Upload>
                <Modal
                    visible={previewVisible}
                    title={previewTitle}
                    footer={null}
                    onCancel={this.handleCancel}>
                    {
                        previewType === 'img' ? <img alt="example" style={{ width: '100%' }} src={previewImage} /> :
                            <video src={previewImage} style={{ width: '100%' }} controls></video>
                    }
                </Modal>
            </>
        );
    }
}

TheUpload.propTypes = {
    disabled: PropTypes.bool,
    len: PropTypes.number,
    label: PropTypes.string,
    getFileResult: PropTypes.func,
    type: PropTypes.string,
    data: PropTypes.object,
    fileType: PropTypes.string,
    maxSize: PropTypes.number,
    imgWidth: PropTypes.number,
    imgHeight: PropTypes.number,
    mode: PropTypes.string,
    accept: PropTypes.array,
    isConversion: PropTypes.bool,
    isShowRemoveIcon: PropTypes.bool,
    fileList: PropTypes.array
}
TheUpload.defaultProps = {
    disabled: false,
    len: 5,
    label: 'Upload',
    type: 'picture-card',
    data: {},
    fileType: 'image',
    maxSize: 10,
    accept: ['image/jpg', 'image/jpeg', 'image/png', 'image/webp', 'image/svg+xml', 'video/mp4'],
    isConversion: true,
    isShowRemoveIcon: true,
    fileList: []
}
export default withRouter(TheUpload)
